package com.xiaotao.learn.algorithm.list;

import com.xiaotao.learn.algorithm.struct.ListNode;

public class AddTwoNumbersTest {
    public static void main(String[] args) {
        ListNode.dump(
                new AddTwoNumbers().addTwoNumbers(
                        ListNode.parse(9,9),
                        ListNode.parse(1)
                )
        );
    }
}

class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        int t = 0;
        ListNode res = l1, cur = l1;
        while(true) {
            t = l1.val + l2.val + carry;
            l1.val = t%10;
            carry = t/10;
            // 若l1已抵达末尾，则直接将l2剩余部分接入到l1末尾
            if (l1.next == null) {
                if (l2.next == null && carry != 0) {
                    l1.next = new ListNode();
                } else {
                    l1.next = l2.next;
                }
                cur = l1.next;
                break;
                // 若l2已抵达末尾，循环结束
            } else if (l2.next == null) {
                cur = l1.next;
                break;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        while(carry != 0) {
            t = cur.val + carry;
            cur.val = t%10;
            carry = t/10;
            if (carry != 0 && cur.next == null) {
                cur.next = new ListNode(carry);
                carry = 0;
            } else {
                cur = cur.next;
            }
        }
        return res;
    }
}
